<template>
  <div class="app-container">
    <!-- 基础工序维护 -->

    <el-row :gutter="24">
      <el-col :lg="24" :xs="24">
        <div class="search-bar">
          <!-- 搜索 -->
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="工序名称" prop="name">
              <el-input
                v-noSpace
                v-model="queryParams.name"
                placeholder="请输入工序名称"
                clearable
                class="!w-[192px]"
                @keyup.enter="handleQuery"
              />
            </el-form-item>

            <el-form-item label="创建时间" prop="timeScopes">
              <el-date-picker
                v-model="queryParams.timeScopes"
                type="datetimerange"
                placeholder="选择日期"
                value-format="YYYY-MM-DD HH:mm:ss"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                clearable
                @change="handleQuery"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
              <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
              <el-button
                type="warning"
                icon="plus"
                @click="handleEdit({}, 'add')"
                v-hasPerm="'sys:basicProcess:edit'"
              >
                新增
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-card shadow="never">
          <el-table v-loading="loading" :data="pageData">
            <el-table-column prop="code" label="工序编码" width="200" align="center" />
            <el-table-column prop="name" label="工序名称" align="center" />

            <el-table-column prop="eachCapacity" label="产能（0.1h）" align="center" />
            <el-table-column prop="personPlan" label="人员需求（人）" align="center" />
            <el-table-column prop="eqptName" label="所需设备" align="center">
              <template #default="{ row }">
                <el-tag
                  v-for="eqptName in row.eqptName?.split(',').slice(0, 1)"
                  :key="eqptName"
                  size="small"
                >
                  {{ eqptName }}
                </el-tag>
                <el-tooltip
                  v-if="row.eqptName?.split(',').length > 1"
                  effect="dark"
                  placement="top"
                >
                  <el-tag type="info">+{{ row.eqptName.split(",").length - 1 }} 更多</el-tag>
                  <template #content>
                    {{ row.eqptName }}
                  </template>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="工序描述" align="center" show-overflow-tooltip />
            <!-- <el-table-column prop="machineCategory" label="设备类别?" align="center"/> -->
            <el-table-column prop="createTime" label="创建时间" align="center" />
            <el-table-column label="操作" fixed="right" width="250" align="center">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="small"
                  link
                  @click="handleEdit(scope.row, 'edit')"
                  v-hasPerm="'sys:basicProcess:edit'"
                >
                  编辑
                </el-button>
                <el-button
                  type="danger"
                  size="small"
                  link
                  @click="handleDel(scope.row)"
                  v-hasPerm="'sys:basicProcess:del'"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 新增/修改弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      @close="handleCloseDialog"
    >
      <el-form
        ref="dialogFormRef"
        :model="dialogParams"
        :inline="true"
        label-width="120px"
        :rules="rules"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="工序名称" prop="name" class="w-90">
              <el-input
                v-noSpace
                v-model="dialogParams.name"
                placeholder="请输入工序名称"
                clearable
                maxlength="100"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="人员需求" prop="personPlan" class="w-90">
              <el-input-number
                :min="1"
                :step="1"
                v-model="dialogParams.personPlan"
                style="width: 100%"
                placeholder="请输入人员需求"
                clearable
              />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="设备" prop="eqptCode" class="w-90">
              <el-select
                v-model="dialogParams.eqptCode"
                placeholder="请选择设备名称"
                clearable
                filterable
                multiple
              >
                <el-option
                  v-for="item in optionsProductName"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="产能（0.1h）" prop="eachCapacity" class="w-90">
              <el-input-number
                v-model="dialogParams.eachCapacity"
                :min="0"
                :step="0.1"
                placeholder="请输入产能"
                clearable
                class="!w-full"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="工作时长（h）" prop="workHour" class="w-90">
              <el-input-number
                v-model="dialogParams.workHour"
                :min="0"
                :max="24"
                :step="1"
                style="width: 100%"
                placeholder="请输入工作时长"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="工序描述" prop="remark" class="w-90">
              <el-input
                v-noSpace
                v-model="dialogParams.remark"
                placeholder="请输入工序描述"
                clearable
                type="textarea"
                :rows="4"
                maxlength="500"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <span class="dialog-footer df">
          <el-button v-debounce="submitDialog" type="primary">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import basicProcessAPI, {
  basicProcessPageQuery,
  basicProcessPageVO,
} from "@/api/basicProcess/basicProcess";
import configApi, { ConfigType } from "@/api/config/config";

import { FormItemRule } from "element-plus/es";

defineOptions({
  name: "User",
  inheritAttrs: false,
});

const queryFormRef = ref(ElForm);

const queryParams = reactive<basicProcessPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

const optionsProductName = ref<{ value: string; label: string }[]>([]); // 显式指定类型

const pageData = ref<basicProcessPageVO[]>();
const total = ref(0);
const listTotal = ref(0);
const loading = ref(false);

// 新增/修改弹窗
const dialog = reactive({
  visible: false,
  title: "",
  type: "",
});
const dialogFormRef = ref(ElForm);

const dialogParams = ref<{
  id: number;
  name: string;
  personPlan: number;
  eqptCode: string[];
  remark: string;
  eachCapacity: number;
  workHour: number;
}>({
  id: NaN,
  name: "",
  personPlan: 0,
  eqptCode: [], // 明确指定为字符串数组
  remark: "",
  eachCapacity: 0,
  workHour: 8,
});

const rules = reactive<Record<string, FormItemRule[]>>({
  name: [{ required: true, message: "工序名称是必填项", trigger: "blur" }],
  personPlan: [{ type: "number", required: true, message: "人员需求是必填项", trigger: "blur" }],
  eqptCode: [{ required: true, message: "设备是必填项", trigger: "blur" }],
  eachCapacity: [{ type: "number", required: true, message: "产能是必填项", trigger: "blur" }],
  workHour: [{ type: "number", required: true, message: "工作时长是必填项", trigger: "blur" }],
  // remark: [{ required: true, message: "工序描述是必填项", trigger: "blur" }],
});
//产品列表 potato carrot beef
const productList = ref<
  {
    codeName: string;
    codeValue: string;
  }[]
>([]);
const getProductName = () => {
  configApi.getConfigListByType(ConfigType.PROD_CODE).then((res) => {
    productList.value = res;
  });
};

// 查询
function handleQuery() {
  // loading.value = true;
  console.log("queryParams", queryParams);
  basicProcessAPI
    .getPage(queryParams)
    .then((data) => {
      pageData.value = [...(data?.list as any)];
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  // queryParams.deptId = undefined;
  // queryParams.createTime = undefined;
  handleQuery();
}

onMounted(() => {
  handleQuery();
  // handleTotal();
});

function handleEdit(row: any, type: any) {
  dialog.type = type;
  getParentCode(row.eqptCode);
  if (type == "edit") {
    dialog.title = "编辑";
    Object.assign(dialogParams.value, { ...row });
    //将eqptCode转为数组
    if (row.eqptCode) {
      dialogParams.value.eqptCode = row.eqptCode.split(",");
    } else {
      dialogParams.value.eqptCode = [];
    }

    console.log("dialogParams.value", dialogParams.value);
  } else {
    dialog.title = "新增";
    clearDialogFormData();
  }
  dialog.visible = true;
}

function handleDel(row: any) {
  ElMessageBox.confirm("确定要删除该工序吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      basicProcessAPI
        .delDialog({ id: row.id })
        .then((data) => {
          ElMessage.success("操作成功");
          handleQuery();
        })
        .catch((err) => {
          // ElMessage.error(`${err}`);
        })
        .finally(() => {
          loading.value = false;
        });
    })
    .catch(() => {
      // 取消删除
    });
}

function handleCloseDialog() {
  dialog.visible = false;
}

//重置弹窗
function clearDialogFormData() {
  let data = {
    id: NaN,
    name: "",
    personPlan: 0,
    eqptCode: [], // 明确指定为字符串数组
    remark: "",
    eachCapacity: 0,
    workHour: 8,
  };
  Object.assign(dialogParams.value, { ...data });
}

// 提交弹窗
function submitDialog() {
  console.log("dialogParams.value", dialogParams.value);

  dialogFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return;
    }
    // 确保 eqptCode 是数组
    const eqptCode = Array.isArray(dialogParams.value.eqptCode)
      ? dialogParams.value.eqptCode.join(",")
      : dialogParams.value.eqptCode;

    let paramsData = <any>{};
    if (dialog.title == "新增") {
      paramsData = {
        name: dialogParams.value.name,
        personPlan: dialogParams.value.personPlan,
        eqptCode: eqptCode,
        eachCapacity: dialogParams.value.eachCapacity,
        workHour: dialogParams.value.workHour,
        remark: dialogParams.value.remark,
      };
    } else {
      paramsData = {
        id: dialogParams.value.id,
        name: dialogParams.value.name,
        personPlan: dialogParams.value.personPlan,
        eqptCode: eqptCode,
        eachCapacity: dialogParams.value.eachCapacity,
        workHour: dialogParams.value.workHour,
        remark: dialogParams.value.remark,
      };
    }

    basicProcessAPI
      .submitDialog(paramsData)
      .then((data) => {
        ElMessage.success("操作成功");
        dialog.visible = false;
        handleQuery();
        clearDialogFormData();
      })
      .catch((err) => {
        // ElMessage.error(`${err}`);
      })
      .finally(() => {
        loading.value = false;
      });
  });
}

const getParentCode = (excludeEqptCode: string | undefined = undefined) => {
  basicProcessAPI
    .getDeviceList({ pageNum: 1, pageSize: 999, bindProcess: true, excludeEqptCode })
    .then((res) => {
      console.log(res, "设备列表");

      optionsProductName.value = res.list.map((item: any) => ({
        value: item.code,
        label: item.name,
      }));
    });
};
</script>

<style lang="scss" scoped>
@use "@/styles/css/public" as *;
</style>
